/**
 *  Copyright (C) 2005 PGT-Linux.org http://www.pgt-linux.org
 *  Author: vandorpe Olivier <vandorpeo@pgt-linux.org>
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

  

int main(int argc,char *argv[])
    {
        int s, t, len;
	int etat,pid;
        struct sockaddr_un remote;
        char str[100];
	
        if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
            perror("socket");
            exit(1);
        }

	if ( argc < 2 ){
	  printf("usage: %s socketFile\n" , argv[0] );
	  exit(4);
	}
	
        printf("Trying to connect...\n");

        remote.sun_family = AF_UNIX;
        strcpy(remote.sun_path, argv[1]);
        len = strlen(remote.sun_path) + sizeof(remote.sun_family);
        if (connect(s, (struct sockaddr *)&remote, len) == -1) {
            perror("connect");
            exit(1);
        }
	//etat=fcntl(s,F_GETFL);
	etat = O_NONBLOCK;
	fcntl(s,F_SETFL,etat);
        printf("Connected.\n");
	if ((pid=fork())<0) {
	  printf("erreur fork\n");
	  return (-1);
	}
	if (pid==0){
	  while(printf("SEND> "), fgets(str, 100, stdin), !feof(stdin)) {
            if (write(s, str,strlen(str)) == -1) {
                perror("send");
                exit(1);
            }
        }
	}else{
	while(1){
		if ((t=read(s, str,100)) >= 0) {
                	str[t] = '\0';
                	if (t>0) printf("RECV> %s", str);
		}
	}
	}
        close(s);

        return 0;
    }
